package com.extweb4j.core.kit;

import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.extweb4j.core.enums.RowStatus;
import com.extweb4j.core.model.ExtLog;
import com.extweb4j.core.model.ExtUser;
import com.jfinal.kit.PropKit;
/**
 * 登录工具类
 * @author Administrator
 *
 */
public class LoginKit {
	/**
	 * 登录
	 * @param request
	 * @return
	 */
	public static String login(HttpServletRequest request,HttpServletResponse response){
		
		String userId  = request.getParameter("userid");
		String password  = request.getParameter("password");
		String captcha = request.getParameter("captcha");
		
		if(StringUtils.isBlank(userId) || StringUtils.isBlank(password)){
			throw new RuntimeException("用户名,密码不能为空");
		}
		
		boolean useCaptcha = PropKit.getBoolean("useCaptcha",false);
		if(useCaptcha){
			if(StringUtils.isBlank(captcha)){
				throw new RuntimeException("验证码不能为空");
			}
			String captchaMd5 =  captcha.toLowerCase();
			Object sessionCaptchaMd5 = request.getSession().getAttribute("captcha");
			if(sessionCaptchaMd5 == null){
				throw new RuntimeException("验证码已过期,请刷新重试");
			}
			System.out.println("用户输入的验证码:"+captchaMd5);
			System.out.println("系统验证码:"+sessionCaptchaMd5.toString().toLowerCase());
			if(!captchaMd5.equals(sessionCaptchaMd5.toString().toLowerCase())){
				throw new RuntimeException("验证码输入错误");
			}
		}
		
		ExtUser user = ExtUser.dao.findUserBy(userId,ExtKit.MD5(password));		
		if(user == null){	
			throw new RuntimeException("用户名或密码错误");	
		}else{
			String userStatus = user.getStr("row_status");
			if(userStatus == null){	
				throw new RuntimeException("您的账号状态异常,暂时无法使用,请联系超级管理员");	
			}else if(userStatus .equals( RowStatus.启用.getState() )){	
				String uid = user.getId();
				Cookie cookie = new Cookie("uid", uid);
				cookie.setMaxAge(7200);
				response.addCookie(cookie);
				//记录日志
				new ExtLog()
		    	.set("id", ExtKit.UUID())
		    	.set("user_name", user.getStr("user_name"))
		    	.set("action_text", "用户登录")
		    	.set("method", "POST")
		    	.set("log_url", "/index/doLogin")
		    	.set("log_params","ip地址:"+IpKit.getIpAddr(request))
		    	.set("create_time", new Timestamp(new Date().getTime()))
		    	.save();
				return uid;
			}	
			throw new RuntimeException("您的账号已被锁定,请联系超级管理员");
		}
	}
	/**
	 * 验证是否登录
	 * @param request
	 * @return
	 */
	public static boolean isLogin(HttpServletRequest request,HttpServletResponse response){
		
//		if(request.getSession().getAttribute("uid") != null){
//			return true;
//		}
		if( getCookie(request,"uid")!= null){
			return true;
		}
		return false;
	}
	/**
	 * 获取cookie
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getCookie(HttpServletRequest request,String name){
		Cookie[] cookies = request.getCookies();
		if (cookies != null)
			for (Cookie cookie : cookies)
				if (cookie.getName().equals(name))
					return cookie.getValue();
		return null;
	}
	/**
	 * 退出
	 * @param request
	 * @return
	 */
	public static boolean logout(HttpServletRequest request){
		
//		request.getSession().removeAttribute("uid"); 
//		request.getSession().invalidate();
		Cookie cookie = new Cookie("uid", null);
		cookie.setMaxAge(0);
		return true;
	}
	
	/**
	 * 验证是否登录
	 * @param request
	 * @return
	 */
	public static ExtUser getSessionUser(HttpServletRequest request){
		
		//Object uid = request.getSession().getAttribute("uid");
		Object uid = getCookie(request,"uid");
		if(uid == null){
			throw new RuntimeException("您的登录已过期,请重新登录");
		}
		
		ExtUser user = ExtUser.dao.findById(uid);
		
		return user;
	}
	/**
	 * 判断是否是超级管理员
	 * @param uid
	 * @return
	 */
	public static boolean isAdmin(String uid){
		
		ExtUser user = ExtUser.dao.findById(uid);
		if(user.getStr("user_id").equals("admin")){
			return true;
		}
		
		return false;
	}
}
